<template>
  <template v-for="item in list" :key="item.name">
    <a-sub-menu
      v-if="item.type === 'dir'"
      :title="item.name"
      :key="item.id"
      @contextmenu.prevent="contextmenuClick(item.id, $event)"
    >
      <template #icon>
        <IconFont :type="item.icon || 'icon-wenjianjiafolder80'" />
      </template>
      <file-list :list="item.children" @contextClick="handleContextClick" />
    </a-sub-menu>
    <a-menu-item
      v-else
      :key="item.id"
      @dblclick="handledbClick(item)"
      @contextmenu.prevent="contextmenuClick(item.id, $event)"
    >
      <template #icon>
        <IconFont :type="item.icon || 'icon-code'" />
      </template>
      {{ item.name }}
    </a-menu-item>
  </template>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import { FileOutlined } from '@ant-design/icons-vue'
import { IFiles } from '@/services/service/files'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'

interface IFile extends IFiles {
  id: number
  children: Array<IFile>
}

export default defineComponent({
  name: 'file-list',
  components: { FileOutlined },
  props: {
    list: {
      type: Array as PropType<IFile[]>,
      default: () => []
    }
  },
  emits: ['contextClick', 'dbClick'],
  setup(props, { emit }) {
    const store = useStore()
    const router = useRouter()

    let childId: number | undefined = undefined

    const contextmenuClick = function (id: number, event: MouseEvent) {
      if (!event) return

      if (childId !== undefined) {
        emit('contextClick', childId)
        childId = undefined
        return
      }

      emit('contextClick', id)
    }

    /** 双击 */
    const handledbClick = function (item: any) {
      store.dispatch('db/setCurrentFile', item)
      router.push('/edit')
    }

    function handleContextClick(id: number) {
      childId = id
    }

    return {
      handledbClick,
      contextmenuClick,
      handleContextClick
    }
  }
})
</script>

<style lang="less" scoped></style>
